package com.ruoyi.business.service.impl;

import java.util.*;

import com.ruoyi.business.domain.District;
import com.ruoyi.business.mapper.DistrictMapper;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import com.ruoyi.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.BussEnvIntroMapper;
import com.ruoyi.business.domain.BussEnvIntro;
import com.ruoyi.business.service.IBussEnvIntroService;

import javax.annotation.Resource;

/**
 * 区域营商环境介绍Service业务层处理
 *
 * @author MagicCube
 * @date 2023-04-28
 */
@Service
public class BussEnvIntroServiceImpl implements IBussEnvIntroService
{
    private static final Logger log = LoggerFactory.getLogger(BussEnvIntroServiceImpl.class);
    @Resource
    private BussEnvIntroMapper bussEnvIntroMapper;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private DistrictMapper districtMapper;

    /**
     * 查询区域营商环境介绍
     *
     * @param id 区域营商环境介绍主键
     * @return 区域营商环境介绍
     */
    @Override
    public BussEnvIntro selectBussEnvIntroById(Long id)
    {
        return bussEnvIntroMapper.selectBussEnvIntroById(id);
    }

    /**
     * 查询区域营商环境介绍列表
     *
     * @param bussEnvIntro 区域营商环境介绍
     * @return 区域营商环境介绍
     */
    @Override
    public List<BussEnvIntro> selectBussEnvIntroList(BussEnvIntro bussEnvIntro)
    {
        Set<String> roles = SecurityUtils.getLoginUser().getRoles();
//        if (roles.contains("admin")) {
//            return bussEnvIntroMapper.selectBussEnvIntroList(bussEnvIntro);
//        }else {
//            bussEnvIntro.setGovernId(SecurityUtils.getUserId());
            return bussEnvIntroMapper.selectBussEnvIntroList(bussEnvIntro);
//        }
    }

    /**
     * 新增区域营商环境介绍
     *
     * @param bussEnvIntro 区域营商环境介绍
     * @return 结果
     */
    @Override
    public int insertBussEnvIntro(BussEnvIntro bussEnvIntro)
    {
//        Set<String> roles = SecurityUtils.getLoginUser().getRoles();
//        if (!roles.contains("admin")){
            bussEnvIntro.setState(0L);
//        }
        bussEnvIntro.setGovernId(SecurityUtils.getUserId());
        bussEnvIntro.setCreateTime(DateUtils.getNowDate());
        return bussEnvIntroMapper.insertBussEnvIntro(bussEnvIntro);
    }

    /**
     * 修改区域营商环境介绍
     *
     * @param bussEnvIntro 区域营商环境介绍
     * @return 结果
     */
    @Override
    public int updateBussEnvIntro(BussEnvIntro bussEnvIntro)
    {
//        Set<String> roles = SecurityUtils.getLoginUser().getRoles();
//        if (!roles.contains("admin")){
//            bussEnvIntro.setState(0L);
//        }
        if (bussEnvIntro.getState()!=null&&bussEnvIntro.getState()!=0){
            BussEnvIntro bussEnvIntro1 = bussEnvIntroMapper.selectBussEnvIntroById(bussEnvIntro.getId());
            bussEnvIntro.setProvinceId(bussEnvIntro1.getProvinceId());
            bussEnvIntro.setCityId(bussEnvIntro1.getCityId());
            bussEnvIntro.setAreaId(bussEnvIntro1.getAreaId());
        }
        bussEnvIntro.setUpdateTime(DateUtils.getNowDate());
        return bussEnvIntroMapper.updateBussEnvIntro(bussEnvIntro);
    }

    /**
     * 批量删除区域营商环境介绍
     *
     * @param ids 需要删除的区域营商环境介绍主键
     * @return 结果
     */
    @Override
    public int deleteBussEnvIntroByIds(Long[] ids)
    {
        //根据ids查询需要删除的区域营商内容
        List<BussEnvIntro> bussEnvIntros = bussEnvIntroMapper.selectBussEnvIntroByIds(ids);
        List<String> pathList = new ArrayList<>();
        for (BussEnvIntro bussEnvIntro : bussEnvIntros) {
            bussEnvIntroMapper.deleteBussEnvRecomById(bussEnvIntro.getId());
            pathList.add(bussEnvIntro.getCover());
        }
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        return bussEnvIntroMapper.deleteBussEnvIntroByIds(ids);
    }

    /**
     * 删除区域营商环境介绍信息
     *
     * @param id 区域营商环境介绍主键
     * @return 结果
     */
    @Override
    public int deleteBussEnvIntroById(Long id)
    {
        bussEnvIntroMapper.deleteBussEnvRecomById(id);
        return bussEnvIntroMapper.deleteBussEnvIntroById(id);
    }

    @Override
    public Map<String, Object> statistics() {
        Map<String, Object> map = new HashMap<>();
        List<BussEnvIntro> bussEnvIntros = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (SecurityUtils.getLoginUser().getRoles().contains("admin")) {
            bussEnvIntros = bussEnvIntroMapper.selectBussEnvIntroList(null);
        }else {
            BussEnvIntro bussEnvIntro = new BussEnvIntro();
            bussEnvIntro.setGovernId(SecurityUtils.getUserId());
            bussEnvIntros = bussEnvIntroMapper.selectBussEnvIntroList(bussEnvIntro);
        }
        map.put("sum",bussEnvIntros.size());
        String yearStart = DateUtils.getYearStart();
        Date year = DateUtils.parseDate(yearStart);
        map.put("year",bussEnvIntros.stream().filter(bussEnvIntro -> bussEnvIntro.getCreateTime().compareTo(year) >= 0).count());
        String monthStart = DateUtils.getMonthStart();
        Date month = DateUtils.parseDate(monthStart);
        map.put("month",bussEnvIntros.stream().filter(bussEnvIntro -> bussEnvIntro.getCreateTime().compareTo(month) >= 0).count());
        String weekStart = DateUtils.getWeekStart();
        Date week = DateUtils.parseDate(weekStart);
        map.put("week",bussEnvIntros.stream().filter(bussEnvIntro -> bussEnvIntro.getCreateTime().compareTo(week) >= 0).count());
        return map;
    }

    private static final List<Long> STATE = Arrays.asList(0L,1L,2L,3L);
    @Override
    public String importUser(List<BussEnvIntro> bussEnvIntroList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(bussEnvIntroList) || bussEnvIntroList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long count = 0L;
        for (BussEnvIntro envIntro : bussEnvIntroList) {
//            //查询省份id
//            District district = new District();
//            district.setPid(0L);
//            district.setName(envIntro.getProvince());
//            List<District> districts = districtMapper.selectDistrictList(district);
//            if (districts.size()>0) {
//                envIntro.setProvinceId(districts.get(0).getId());
//                district.setPid(districts.get(0).getId());
//            } else {
//                district.setPid(null);
//            }
//            //查询城市id
//            district.setName(envIntro.getCity());
//            List<District> districts1 = districtMapper.selectDistrictList(district);
//            if (districts1.size()>0) {
//                envIntro.setCityId(districts1.get(0).getId());
//                district.setPid(districts1.get(0).getId());
//            } else {
//                district.setPid(null);
//            }
//            //查询区域
//            district.setName(envIntro.getArea());
//            List<District> districts2 = districtMapper.selectDistrictList(district);
//            if (districts2.size()>0) {
//                envIntro.setCityId(districts2.get(0).getId());
//                district.setPid(districts2.get(0).getId());
//            }
            count++;
            if (count.equals(1L)&&envIntro.getGovernName().equals("xxx政府")){
                count=0L;
                continue;
            }
            try{
                if (envIntro.getState()==null||STATE.contains(envIntro.getState())){
                    envIntro.setState(0L);
                }
                if (envIntro.getGovernId()==null){
                    envIntro.setGovernId(SecurityUtils.getUserId());
                }
                if (envIntro.getGovernName()==null||envIntro.getGovernName().equals("")){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + count + "条数据 缺少政府名称");
                    break;
                }
                envIntro.setCreateBy(SecurityUtils.getUsername());
                envIntro.setCreateTime(DateUtils.getNowDate());
                bussEnvIntroMapper.insertBussEnvIntro(envIntro);
                successNum++;
                successMsg.append("<br/>" + successNum + "、政府 " + envIntro.getGovernName() + " 导入成功");
            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、政府 " + envIntro.getGovernName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
        /*
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
         */
//        return null;
    }
}
